package com.server;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * 主要把LogicServer发送过来的数据发送至gateway
 * 
 * @author Simple
 * @date 2013-7-5 下午03:40:26
 * @Description TODO
 */
public class MyLogicClientHandler extends IoHandlerAdapter {

  private MyLogicServer logicServer;

  public MyLogicClientHandler(MyLogicServer logicServer) {
    this.logicServer=logicServer;
  }

  private Logger log=Logger.getLogger(this.getClass());

  public void exceptionCaught(IoSession session, Throwable arg1) throws Exception {
  }

  public void messageReceived(IoSession session, Object obj) throws Exception {
    log.debug("[LogicClient receive message]");
  }

  public void messageSent(IoSession session, Object obj) throws Exception {
    log.debug("[LogicClient send message] to gateway");
    log.debug("LogicServer-Connector管理Session个数：" + logicServer.getConnector().getManagedSessionCount());
  }

  public void sessionClosed(IoSession session) throws Exception {
    log.debug("[LogicClient closed session] the gateway is shutdown");
    boolean reconnection=false;
    for(int i=0; i < 10; i++) {// 10s后重连,自动连接10次
      Thread.sleep(10000);
      if(logicServer.reconnection(session)) {
        reconnection=true;
        break;
      }
    }
    if(!reconnection) {
      logicServer.shutDownConnector();
      logicServer.shutDownAcceptor();
    }
  }

  public void sessionCreated(IoSession session) throws Exception {
    log.debug("[LogicClient create session]");
  }

  public void sessionIdle(IoSession session, IdleStatus arg1) throws Exception {
    log.debug("[LogicClient idle]");
  }

  public void sessionOpened(IoSession session) throws Exception {
    log.debug("[LogicClient opened session]");
  }

  public void setLogicServer(MyLogicServer logicServer) {
    this.logicServer=logicServer;
  }

  public MyLogicServer getLogicServer() {
    return logicServer;
  }
}
